<template>
  <div class="flex items-center gap2 pr10px">
    <ElButton link @click="switchTo">切换到</ElButton>
    <ElButton v-if="userStore.isSwitch" link @click="endSwitch">返回</ElButton>
    <ElDropdown trigger="click">
      <div class="flex items-center gap2">
        <!-- <img src="@/assets/imgs/avatar.jpg" class="w-25px rounded-50%" /> -->
        <Avatar width="25px" :filepath="userStore.avatar" class="rounded-50%"/>
        <ElButton link>{{ userStore.name }}</ElButton>
      </div>
      <template #dropdown>
        <ElDropdownMenu>
          <ElDropdownItem>
            <div>项目文档</div>
          </ElDropdownItem>
          <ElDropdownItem divided>
            <div>锁定屏幕</div>
          </ElDropdownItem>
          <ElDropdownItem>
            <div @click="logout">退出系统</div>
          </ElDropdownItem>
        </ElDropdownMenu>
      </template>
    </ElDropdown>
  </div>
</template>
<script setup lang="ts">
  import { ElDropdown, ElDropdownMenu, ElDropdownItem, ElButton } from 'element-plus';
  import { Avatar } from '@/components/avatar'
  import { useUserStore, useTagsViewStore } from '@/store'
  import { endSwitchApi, logoutApi } from '@/api'
  import { useRouter } from 'vue-router';
  import feedback from '@/utils/feedback';
  import { popup } from '@/components/Popup';
  import { Switchable } from '@/components/Switchable';

  const userStore = useUserStore()
  const router = useRouter()
  function switchTo() {
    popup(Switchable, { title: '切换到'})
  }

  async function endSwitch() {
    await endSwitchApi()
    await userStore.endSwitch()

    const tagsViewStore: any = useTagsViewStore()
    tagsViewStore.delAllViews()
    feedback.msgSuccess('操作成功')
  }

  async function logout() {
    try{
      await feedback.confirm('确定要退出系统吗?')
      await logoutApi()
      const tagsViewStore: any = useTagsViewStore()
      tagsViewStore.delAllViews()
      userStore.logout()
      router.replace('/login')
    } catch(e) {
      //
    }
  }
</script>